package com.xm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xm.entity.UserP;
import com.xm.mapper.UserMapper;
import com.xm.service.UserService;
import com.xm.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserP> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserP getByName(String name) {
        return this.userMapper.getByName(name);
    }

    @Override
    public UserP getById2(Long id) {
        return this.userMapper.getById2(id);
    }

    @Override

    public int add(UserP user) throws Exception {
        UserP existedOne = this.userMapper.getByName(user.getName());
        if (existedOne != null) {
            return -2;//用户已存在
        }
        return this.userMapper.add(user);
    }

    @Override
    @Transactional
    public void batchAdd(List<UserP> list) throws Exception {
        //测试事务回滚 删除一条数据
//        int rev = this.userMapper.deleteById(35L);//出错会一起回滚
//        log.info("batchAdd deleteById rev={}", rev);
//        boolean bool = this.removeById(35L);//出错会一起回滚
//        log.info("batchAdd deleteById bool={}", bool);

        //外层先确认name不重复，批量新增时不再校验
        if(!CollectionUtils.isEmpty(list)){
            //执行sql语句不宜过长，据说单批次处理超过1000条数据会异常；这里给一个默认值500
            List<List<?>> chunks = StringUtil.groupBatchSize(list, 1000);
            for (List<?> users : chunks) {
                this.userMapper.batchAdd((List<UserP>) users);
            }
        }
    }

    @Override
    @Transactional
    public int update(UserP user) throws Exception {
        UserP existedOne = this.userMapper.getByName(user.getName());
        if(existedOne != null && !existedOne.getId().equals(user.getId())){
            return -2;//用户已存在
        }
        return this.userMapper.update(user);
    }

    @Override
    public List<UserP> getByPage(String name, int limit, int offset) {
        return this.userMapper.getByPage(name, limit, offset);
    }
}
